<template>
    <common-dialog :dialogVisible="dialogVisible" width="90%" :title="'交付物汇总'" @cancel="cancel" @ok="ok">
      <div class="drawer-content">
        <div class="title-box">
          <div class="left-box">
            应交付{{deliverablesData.toBeQuantity}}项，实际交付<span class="actualQuantity">{{deliverablesData.actualQuantity}}</span>项，完成率{{deliverablesData.completionRate}}
          </div>
          <div class="right-box">
            <span style="padding-right: 9px;">选择项目阶段：</span>
            <a-select 
              show-search
              style="width:172px;"
              option-filter-prop="children"
              :filter-option="filterOption"
              :allowClear="true"
              placeholder="请选择"
              v-model="filterFourthNodeName"
              @change="setFilterTableData">
              <a-select-option v-for="(item,index) in fieldData" :key="item.name">
                {{item.value}}
              </a-select-option>
              <a-icon slot="clearIcon" type="close" @click="filterFourthNodeName = 'ALL'"></a-icon>
            </a-select>
            <a-button class="import-btn" @click="exportBtn">导出交付物清单</a-button>
          </div>
        </div>
        <common-table
          ref="table"
          :columns="columns"
          :tableData="filterTableData"
          :selectType="'checkbox'"
          data-row-key="oid"
          :isRowsSelectVisible="isRowsSelectVisible"
          :loadVisible="loadVisible"
          :hasAttention="hasAttention"
          :this-table-name="'porjectManageList'"
          :this-table-header-data="thisTableHeaderData"
          :this-table-header-data-middel="thisTableHeaderDataMiddel"
          :setRowColor="true"
          @routerPage="routerPage"
          @selectedRows="selectedRows"
          @clickRow="clickRow"
        ></common-table>
      </div>
    </common-dialog>
</template>
<script>
import commonDialog from '@/components/common/commonDialog'
import commonTable from "@/components/common/commonTable";
import { summaryDeliverabes } from'@/api/projectPlan.js'
import { exportList } from "@/api/projectManage.js";
import { saveFile } from '@/utils/util'
import copyACtion from '@/views/singleProject/fileSingle/el-common-js/copy'
import {mapGetters} from 'vuex'
const columns = [
  {
    name: 'fourthNodeName',
    displayName: '四级汇总节点',
    key: 'fourthNodeName',
    fieldType: 'Select',
    dataType: 'String',
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender"
    }
  },
  {
    displayName: '任务名称',
    name: 'activityName',
    key: 'activityName',
    fieldType: 'Select',
    dataType: 'String',
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender"
    }
  },
  {
    displayName: '交付物要求',
    key: 'deliverableName',
    name: 'deliverableName',
    fieldType: 'Select',
    dataType: 'String',
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender"
    }
  },
  {
    displayName: '实际交付编号',
    name: 'targetObjectNumber',
    key: 'targetObjectNumber',
  },
  {
    displayName: '实际交付内容',
    name: 'targetObjectName',
    key: 'targetObjectName',
    scopedSlots: {
      customRender: "name",
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon", 
    }
  },
  {
    displayName: '交付物状态',
    name: 'targetObjectState',
    key: 'targetObjectState',
    fieldType: 'Select',
    dataType: 'String',
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender"
    }
  },
  {
    displayName: '任务执行人',
    name: 'primaryResource',
    key: 'primaryResource',
  },
  {
    displayName: '交付物签批人',
    name: 'reviewer',
    key: 'reviewer',
  },
  {
    displayName: '目标完成时间',
    key: 'activityTargetEndDate',
    fieldType: 'Date',
    name: 'activityTargetEndDate',
    dataType: 'String',
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender"
    }
  },
  {
    displayName: '实际完成时间',
    key: 'activityActualEndDate',
    fieldType: 'Date',
    dataType: 'String',
    name: 'activityActualEndDate',
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender"
    }
  },
  {
    fieldType: 'Date',
    displayName: '交付物修改时间',
    name: 'deliverableModifyDate',
    key: 'deliverableModifyDate',
    dataType: 'String',
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender"
    }
  },
  {
    displayName: '交付物修改者',
    fieldType: 'Select',
    name: 'deliverableModifier',
    key: 'deliverableModifier',
    dataType: 'String',
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender"
    }
  },
  // {
  //   displayName: '序号',
  //   name: 'lineNumber',
  //   key: 'lineNumber',
  // },
  // {
  //   dataIndex: "setting",
  //   fixed: "right",
  //   slots: {
  //     title: "customTitle"
  //   },
  //   width: 40
  // }
]
export default {
  components: { commonDialog, commonTable },
  mixins: [copyACtion],
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    oid: {
      type: String,
      default: ''
    }
  },
  computed: {
    ...mapGetters({
      'fileSingleData': 'fileSingle'
    })
  },
  data() {
    return {
       /**表格操作参数 */
      isRowsSelectVisible: true, // 是否显示表格的选择列
      columns: columns,
      tableData: [],
      filterTableData: [],
      loadVisible: false,
      hasSelectTableData: [], // 表格已选中数据
      hasAttention: [], // 已关注数据
      thisTableHeaderData: [],//当前表格所有表头数据
      thisTableHeaderDataMiddel: [],//当前表格存在中台的表头数据
      deliverablesData: {},
      fieldData: [
        {
          name: 'ALL',
          value: '全部'
        }
      ],
      filterFourthNodeName: ''
    }
  },
  watch: {
    dialogVisible(val) {
      if (val && this.$refs.table) {
        this.$refs.table.selectedRowKeys = [] // 讲选中的置空
      }
    }
  },
  mounted() {
    if (this.oid) {
      this.getTableData()
    }
  },
  methods: {
    exportBtn() {
      let arr = []
      this.columns.map((item, index) => {
        if (item.dataIndex !== 'setting') {
          arr.push({
            name: item.name,
            title: item.title,
            num: index + 1
          })
        }
      })
      let data = {
        "titles" : arr,
        "projects": this.tableData
      }
      exportList(data).then(res => {
        if (res && res.status === 200) {
          const blob = new Blob([res.data], {type: 'application/octet-stream'})
          saveFile(blob, '交付物清单.xlsx')
        } else {
          this.$message.warn('导出异常')
        }
      })
    },
    //点击交付物--跳转至交付物详情页面
    routerPage(val) {
      if (val.targetObjectOid.includes('ProjectTaskBook')) {
        // 任务书详情页
        this.$router.push({path: "projectPaper/mainTaskBook"})
      } else {
        val.oid = val.targetObjectOid
        val.state = val.targetObjectState
        // console.log('交付物要求跳转------------跳转至“文件”：', val)
        //交付物页面（详情界面）
        this.fileSingleData.tableArr = [val]
        this.setFileSingle(this.fileSingleData)
        this.setFileSingleTableItem({oid: val.oid, state: val.state})
        this.$store.commit('SET_PROJECT_FILE_TITLE', '')
        this.$router.push({path: "fileSingle/examineProject"})
      }
    },
    getTableData() {
      let params = {
        oid: this.oid
        // oid: "com.pisx.pmgt.plan.PIPlan:1083338"
      }
      this.loadVisible = true
      summaryDeliverabes(params).then(res => {
        this.loadVisible = false
        if (res.status === 200) {
          if (res.data.data && res.data.data.length > 0) {
            this.deliverablesData = res.data.data[res.data.data.length - 1]
            // this.tableData = res.data.data.slice(0, res.data.data.length - 1)
            this.tableData = _.orderBy(res.data.data.slice(0, res.data.data.length - 1), ['activityTargetEndDate'], ['asc'])//按照创建时间降序排序
            
            let selectedData = []
            this.tableData.forEach(item => {
              if (item.fourthNodeName && !selectedData.map(items => items.name).includes(item.fourthNodeName)) {
                selectedData.push({
                  name: item.fourthNodeName,
                  value: item.fourthNodeName
                })
              }
            })
            this.fieldData.push(...selectedData)
            this.setFilterTableData()
            // console.log(this.tableData)
            // 设置筛选下拉框选项
            let { keyArr, info } = this.setFilterSelect(this.tableData, {
              fourthNodeName: [],
              deliverableName: [],
              targetObjectState: [],
              activityName: [],
              deliverableModifier: []
            })
            this.columns.forEach((item, index) => {
              if (keyArr.includes(item.name)) {
                this.columns[index].fieldValue = info[item.name]
              }
            })
            // 设置筛选下拉框选项
          }
        } else {
          this.tableData = []
          this.filterTableData = []
          this.loadVisible = false
          this.$message.error('获取数据失败')
        }
      }).catch(error => {
        this.tableData = []
        this.filterTableData = []
        this.loadVisible = false
        this.$message.error('获取数据接口异常')
      })
    },
    setFilterTableData() {
      if (!this.filterFourthNodeName || this.filterFourthNodeName === 'ALL') {
        this.filterTableData = this.tableData
      } else {
        this.filterTableData = this.tableData.filter(item => this.filterFourthNodeName === item.fourthNodeName)
      }
      this.setDeliverablesData()
    },
    setDeliverablesData() {
      this.deliverablesData.toBeQuantity = this.filterTableData.length
      let actualQuantity = 0
      this.filterTableData.forEach(item => {
        if(item.targetObjectName) {
          actualQuantity++
        }
      })
      this.deliverablesData.actualQuantity = actualQuantity
      this.deliverablesData.completionRate = (((actualQuantity / this.deliverablesData.toBeQuantity) * 100).toFixed(2)) + '%'
    },
    setFilterSelect(data, info) {
      let keyArr = Object.keys(info)
      data.forEach(item => {
        keyArr.forEach(it => {
          if (item[it] && !info[it].includes(item[it])) {
            info[it].push(item[it])
          }
        })
      })
      return {
        keyArr,
        info
      }
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    // 选中数据
    selectedRows(val) {
      this.hasSelectTableData = val
    },
    clickRow(val) {
      this.hasSelectTableData = val
    },
    cancel() {
      this.$emit('cancel')
    },
    ok() {
      this.$emit('ok')
    }
  }
}
</script>
<style lang="less" scoped>
  .my-dialog{
    .title-box{
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 10px;
      .actualQuantity{
        color: #386BD7;
      }
      .right-box{
        display: flex;
        align-items: center;
        .import-btn{
          margin-left: 14px;
        }
      }
    }
    /deep/ .ant-modal-body{
      padding: 10px 24px;
    }
  }
  
</style>